package com.pet.article.listener;

import com.alibaba.fastjson.JSON;
import com.pet.article.feign.ApUserArticleFeign;
import com.pet.common.constants.MQConstants;
import com.pet.model.user.pojos.ApUserArticle;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
import java.util.Optional;

@Component
public class ArticleIsLabelListener {

    @Autowired
    private ApUserArticleFeign userArticleFeign;

    @KafkaListener(topics = MQConstants.ARTICLE_LABEL_USER_TOPIC)
    public void receiveMessage(ConsumerRecord<?, ?> record) {
        Optional<? extends ConsumerRecord<?, ?>> optional = Optional.ofNullable(record);
        if (optional.isPresent()) {
            String value = (String) record.value();
            //转换Map集合
            Map map = JSON.parseObject(value, Map.class);
            Long articleId = (Long) map.get("articleId");
            Integer userId = (Integer) map.get("userId");
            Integer operation = (Integer) map.get("operation");
            if (operation.equals(0)) {
                ApUserArticle userLabel = new ApUserArticle();
                userLabel.setUserId(userId);
                userLabel.setArticleId(Long.valueOf(String.valueOf(articleId)));
                userLabel.setCreatedTime(new Date());
                userArticleFeign.save(userLabel);
            }
            if (operation.equals(1)) {
                ApUserArticle userLabel = new ApUserArticle();
                userLabel.setUserId(userId);
                userLabel.setArticleId(Long.valueOf(String.valueOf(articleId)));
                userArticleFeign.delete(userLabel);
            }

        }
    }
}